from rest_framework.fields import SerializerMethodField

from shopping.models import Classification,Commodity,CommodityImg,ShoppingCart,Order,OrderGoods,Payment
from rest_framework import serializers, viewsets


class ClassificationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Classification
        # fields = '__all__'
        exclude = ['create_time', 'update_time','is_delete']

# 根据一级分类得到所有的子级分类   班级得学生的数据
class ClassificationSerializerSimple(serializers.ModelSerializer):
    classification_set = ClassificationSerializer(many=True, read_only=True)
    class Meta:
        model = Classification
        # fields = '__all__'
        fields = ['id', 'classification_set','name']

# 商品图片序列器
class CommodityImgSerializer(serializers.ModelSerializer):
    class Meta:
        model = CommodityImg
        fields = ["src"]

# 商品序列器
class CommoditySerializer(serializers.ModelSerializer):
    # 一级分类 二级分类  商品图片的地址
    classification1_name = serializers.CharField(read_only=True, source="classification1.name")
    classification2_name = serializers.CharField(read_only=True, source="classification2.name")
    commodityimg_set = CommodityImgSerializer(many=True, read_only=True)
    class Meta:
        model = Commodity
        exclude = ['create_time', 'update_time','is_delete']
        extra_kwargs = {
            'sales':{'read_only':True},
            'comments':{'read_only':True},
        }

#购物车序列化器
class ShoppingCartSerializer(serializers.ModelSerializer):
    # 添加商品详情的展示  数据来源  ==》get_commodityDetail  方法查询得到
    commodityDetail = SerializerMethodField()
    class Meta:
        model = ShoppingCart
        fields = '__all__'

    def validate(self,attrs):
        # attr ==> {number: 1, commodity: "5"}
        if attrs['number'] < 0:
            raise serializers.ValidationError("商品数量不能小于0")
        # attr["number"] 加入购物车的商品数量  和 商品的库存
        if attrs['number'] > attrs["commodity"].stock:
            raise serializers.ValidationError("库存不足")
        return attrs

    # 固定参数  参数一定是当前操作的模型
    def get_commodityDetail(self,shoppingcart):  # 吧当前的模型对象传入 购物车模型对象
        #通过购物车正向查询商品
        return CommoditySerializer(shoppingcart.commodity).data

#订单序列化器
class OrderSerializer(serializers.ModelSerializer):
    class Meta:
        model = Order
        fields = '__all__'

        # extra_kwargs = {
        #     'order_id':{'read_only':True},
        #     'total_count':{'read_only':True},
        #     'total_amount':{'read_only':True},
        #     'status':{'read_only':True},
        #     'user':{'read_only':True},
        # }
        #设置只读
        read_only_fields=['order_id','status','total_count','total_amount','status','user']

#支付凭证序列化器
class PaymentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Payment
        fields = '__all__'



